#include <bits/stdc++.h>

#define eb emplace_back
#define ep emplace
#define fi first
#define se second
#define in read<int>()
#define lin read<ll>()
#define rep(i, x, y) for(int i = (x); i <= (y); i++)
#define per(i, x, y) for(int i = (x); i >= (y); i--)

using namespace std;

using ll = long long;
using db = double;
using pii = pair < int, int >;
using vec = vector < int >;
using veg = vector < pii >;

template < typename T > T read() {
	T x = 0; bool f = 0; char ch = getchar();
	while(!isdigit(ch)) f |= ch == '-', ch = getchar();
	while(isdigit(ch)) x = x * 10 + (ch ^ 48), ch = getchar();
	return f ? -x : x;
}

template < typename T > void chkmax(T &x, const T &y) { x = x > y ? x : y; }
template < typename T > void chkmin(T &x, const T &y) { x = x < y ? x : y; }

const int N = 5010;

int f[N], a[N], pos[N], n;

struct BIT {
	int tr[N];
	void add(int x, int v) { for(; x <= n; x += x & -x) tr[x] += v; }
	int query(int x) { int res = 0; for(; x; x -= x & -x) res += tr[x]; return res; }
	int query(int l, int r) { return query(r) - query(l - 1); }
} T1, T2;

int main() {
#ifndef ONLINE_JUDGE
	freopen("1.in", "r", stdin);
#endif
	n = in; rep(i, 1, n) pos[a[i] = in] = i;
	memset(f, 0x3f, sizeof f); f[0] = 0;
	rep(i, 1, n) {
		int res = 0; 
		rep(j, 1, i) T1.add(pos[j], 1);
		per(j, i, 1) {
			res += T1.query(pos[j], n) - 1;
			T1.add(pos[j], -1);
			res -= T2.query(1, pos[j]);
			res += T2.query(pos[j], n);
			T2.add(pos[j], 1);
			chkmin(f[i], res + f[j - 1]);
		} rep(j, 1, i) T2.add(pos[j], -1);
		//	cerr << f[i] << endl;
	} printf("%d\n", f[n]);
	return 0;
}
